import logging

from pylons import request, response, session
from pylons import tmpl_context as c
from pylons.controllers.util import abort, redirect_to, url_for
from pylons.templating import render_mako as render

import sqlalchemy as sa
from sqlalchemy import orm

from quickwiki.lib.base import BaseController
from quickwiki.model import meta, Page, wikiwords

log = logging.getLogger(__name__)

class PageController(BaseController):

    def index(self, title):
        page_q = meta.Session.query(Page)
        page = page_q.filter_by(title=title).first()
        if page:
            c.content = page.get_wiki_content()
            return render('/page.mako')
        elif wikiwords.match(title):
            return render('/new_page.mako')
        abort(404)

    def edit(self, title):
        page_q = meta.Session.query(Page)
        page = page_q.filter_by(title=title).first()
        if page:
            c.content = page.content
        return render('/edit.mako')

    def save(self, title):
        page_q = meta.Session.query(Page)
        page = page_q.filter_by(title=title).first()
        if not page:
            page = Page()
            page.title = title
        page.content = request.POST.get('content','')
        c.title = page.title
        c.content = page.get_wiki_content()
        c.message = 'Successfully saved'
        meta.Session.save_or_update(page)
        meta.Session.commit()
        return render('/page.mako')

    def list(self):
        c.titles = [page.title for page in meta.Session.query(Page).all()]
        return render('/list.mako')

    def delete(self):
        page_q = meta.Session.query(Page)
        title = request.POST['id']
        page = page_q.filter_by(title=title).one()
        meta.Session.delete(page)
        meta.Session.commit()
        c.titles = page_q.all()
        return render('/list-titles.mako')
